package com.alibaba.otter.canal.adapter.launcher.rest;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 用于获取rabbitmq连接的工具类
 * 配置需在该工具类中进行设置
 *
 * 也有发消息的方法
 */
public class RabbitConnectionUtil {
    public static Connection getConnection() throws IOException, TimeoutException {
        // 定义一个连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 设置服务地址
        factory.setHost("10.100.50.14");
        // 设置端口号 AMQP 5672
        factory.setPort(5672);
        // vhost
        factory.setVirtualHost("/testhost");
        // 用户名，密码
        factory.setUsername("admin");
        factory.setPassword("admin");
        // 返回MQ连接
        return factory.newConnection();
    }
    public static boolean sendMqMsg(String exchange,String routingKey,byte[] msg){
        try(Connection conn=RabbitConnectionUtil.getConnection()){
            try(Channel channel=conn.createChannel()){
                channel.basicPublish(exchange,routingKey,null,msg);
            }
        }catch (Exception e){
            System.out.println("something wrong with the connection of rabbit.");
            e.printStackTrace();
        }
        return true;
    }
}
